import { createChunk } from "./createChunk";
import { getFileHash } from "./fileHash";

self.onmessage = async (e) => {
  const { type, file, chunkSize, startIndex, endIndex, chunkList } = e.data;

  /** ========= 获取分片 ======== */
  if (type === "getChunks") {
    /** 存储所有的异步操作 */
    let promises: any[] = [];

    /** 将所有异步操作添加到promises中 */
    for (let i = startIndex; i < endIndex; i++) {
      promises.push(createChunk(file, chunkSize, i));
    }

    /** 等待所有异步操作完成，并接受结果数组 */
    const chunks = await Promise.all(promises);

    /** 所有异步操作完成，向主线程发送消息 */
    self.postMessage({ type: "getChunks", chunks });
  }

  /** ===== 获取文件hash ===== */
  /** 分片完成后计算文件的hash */
  if (type === "getFileHash") {
    const fileHash = await getFileHash(chunkList);
    self.postMessage({ type: "getFileHash", fileHash });
  }
};
